<template>
  <div>
    <!-- 头部查询 start -->
    <el-form ref="queryForm" class="query-form" :model="queryParams" inline size="small">
      <el-form-item label="渠道" prop="channel_id" class="big-query">
        <el-cascader
          v-model="queryParams.channel_id"
          :options="channelOpts"
          :props="{ multiple: true,emitPath:false }"
          style="width: 260px"
          collapse-tags
          :show-all-levels="false"
          clearable
          filterable
          @change="handleQuery"></el-cascader>
      </el-form-item>

      <el-form-item class="big-query" label="活动时间" prop="dateRange" size="small">
        <el-date-picker v-model="queryParams.dateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleQuery">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部" @change="handleQuery">
          <el-option :key="0" label="全部" :value="0" />
          <el-option v-for="it in statusOpts" :key="it.value" :label="it.label" :value="it.value" />
        </el-select>
      </el-form-item>

      <el-form-item class="big-query" label="关键词" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="请输入活动名" clearable style="width: 210px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 头部查询 end -->

    <!-- 头部操作栏 start -->
    <el-button type="primary"
      icon="el-icon-plus"
      style="margin-bottom:10px"
      size="small"
      @click="handleAdd">新增</el-button>
    <!-- 头部操作栏 end -->

    <!-- 数据表格 start -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="活动ID" prop="id" width="80"/>
      <el-table-column label="活动名称" prop="name" show-overflow-tooltip/>
      <el-table-column label="活动描述" prop="describe" show-overflow-tooltip/>
      <el-table-column label="活动时间" width="330">
        <template slot-scope="scope">
          {{ scope.row.start_time|parseTime }} ~ {{ scope.row.stop_time|parseTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status===3? 'info' : scope.row.status===2?'success':''">
            {{ scope.row.status|translateToName(statusOpts) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"
        width="200"
        fixed="right"
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="small"
            type="text"
            @click="handleDetail(scope.row)">查看</el-button>
          <el-button
            v-if="canEdit(scope.row)"
            size="small"
            type="text"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            v-if="scope.row.status===2"
            size="small"
            type="text"
            @click="handleStop(scope.row)">结束</el-button>
          <el-button
            v-else
            size="small"
            type="text"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.page_size" @pagination="getList" />
    <!-- 数据表格 end -->

    <!-- 添加或修改对话框 start -->
    <el-dialog :title="title"
      :visible.sync="open"
      width="700px"
      custom-class="activity-add-edit-dialog"
      :close-on-click-modal="false">
      <el-form ref="form"
        :model="form"
        :rules="rules"
        style="padding-right: 20px;"
        class="input-form-fill"
        label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动" prop="act_fixed_id">
              <el-select v-model="form.act_fixed_id" @change="getProductOpsByAppId" :disabled="!!form.id">
                <el-option v-for="it in activityOpts" :key="it.value" :label="it.label" :value="it.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最低版本" prop="min_version">
              <el-input v-model.trim="form.min_version" :disabled="!!form.id"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="活动名" prop="name">
          <el-input v-model.trim="form.name"/>
        </el-form-item>
        <template v-if="'markup-price' === form.act_fixed_id">
          <el-row>
            <el-col :span="12" >
              <el-form-item label="价格" prop="setting.price" required>
                <el-input-number v-model="form.setting.price" :precision="2" :min="0.00"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" >
              <el-form-item label="划线展示价" prop="setting.origin_price">
                <el-input-number v-model="form.setting.origin_price" :precision="2" :min="0.00"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="展示形式" prop="setting.show-type" required>
                <el-radio-group v-model="form.setting['show-type']">
                  <el-radio :label="1">最多选中一个</el-radio>
                  <el-radio :label="2">同时选中多个</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <el-form-item label="活动标题" prop="setting.title" v-if="['limit_t_dis'].includes(form.act_fixed_id)">
          <el-input v-model.trim="form.setting.title"/>
        </el-form-item>

        <el-form-item label="描述" prop="describe">
          <el-input v-model.trim="form.describe"/>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="项目" prop="app_id">
              <el-select v-model="form.app_id" @change="getProductOpsByAppId" multiple collapse-tags>
                <el-option v-for="item in permission_projectList" :value="item.app_id" :label="item.name" :key="item.app_id" :disabled="form.act_fixed_id==='10001'&&item.app_id!==22"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="渠道" prop="channel_id">
              <el-cascader
                v-model="form.channel_id"
                :options="permission_projectList"
                :props="{ multiple: true,emitPath:false }"
                collapse-tags
                :show-all-levels="false"
                filterable
                clearable></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="活动时间" prop="dateRange">
          <el-date-picker v-model="form.dateRange"
            type="datetimerange"
            value-format="yyyy-MM-dd HH:mm:ss"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </el-form-item>
        <!-- limit_t_dis：限时优惠活动 -->
        <template v-if="['10004','limit_t_dis','pg-code','vip-discount','markup-price'].includes(form.act_fixed_id)">
          <el-form-item label="权益套餐" prop="product_ids" key="10004_product_ids">
            <el-select v-model="form.product_ids"
              placeholder="请选择"
              multiple
              collapse-tags
              filterable
              @change="setProductPrice">
              <el-option v-for="item in productData" :key="item.id" :label="item.show_name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-row>
            <template v-if="form.act_fixed_id === '10004'">
              <el-col :span="12">
                <el-form-item label="新用户价格" prop="new_user_price">
                  <el-input-number v-model="form.new_user_price" :precision="2" :min="0.01"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="老用户价格" prop="old_user_price">
                  <el-input-number v-model="form.old_user_price" :precision="2" :min="0.01"/>
                </el-form-item>
              </el-col>
            </template>
            <template v-else-if="['pg-code','markup-price'].includes(form.act_fixed_id)">
              <el-form-item label="奖品配置" prop="reward_id">
                  <el-select v-model="form.reward_id" placeholder="请选择奖品"
                    multiple
                    filterable
                    remote
                    :remote-method="getRewardList">
                    <el-option v-for="item in rewardOptionList.filter(item => item.status === 'valid')" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="消息标题" prop="title">
                <el-input v-model="form.setting.msg_title" placeholder="请输入消息标题"></el-input>
              </el-form-item>
              <el-form-item label="消息模板" prop="template">
                <Editor :content.sync="form.template"></Editor>
              </el-form-item>
            </template>
            <template v-else-if="'limit_t_dis' === form.act_fixed_id">
              <el-col :span="12" v-show="form.product_ids.length === 1">
                <el-form-item label="原价" prop="setting.origin_price">
                  <el-input v-model="productOriginPrice" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="form.product_ids.length === 1">
                <el-form-item label="现价" prop="setting.price">
                  <el-input v-model="productPrice" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="秒杀价" prop="setting.price">
                  <el-input-number v-model="form.setting.price" :precision="2" :min="0.01"/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="用户分群" prop="ug_ids">
                  <el-select
                      multiple
                      filterable
                      v-model="form.ug_ids"
                      @keydown.native.delete.capture.stop.prevent
                      collapse-tags
                      no-data-text="无数据,请尝试选择其他项目"
                      popper-class="w500"
                      placeholder="请选择用户分群">
                      <el-option v-for="item in userGroupList"
                        :key="item.id"
                        :label="item.id+'  '+item.name"
                        :value="item.id"/>
                    </el-select>
                </el-form-item>
              </el-col>
            </template>
            <template v-else-if="'vip-discount' === form.act_fixed_id">
              <el-col :span="12" v-show="form.product_ids.length === 1">
                <el-form-item label="原价" prop="setting.origin_price">
                  <el-input v-model="productOriginPrice" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-show="form.product_ids.length === 1">
                <el-form-item label="现价" prop="setting.price">
                  <el-input v-model="productPrice" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="会员购买价" prop="setting.price">
                  <el-input-number v-model="form.setting.price" :precision="2" :min="0.01"/>
                </el-form-item>
              </el-col>
            </template>
          </el-row>
        </template>
        <!-- <template v-else-if="[''].includes(form.act_fixed_id)">
          <el-form-item label="试用时间" prop="duration">
            <el-input-number v-model="form.duration" :precision="0" :min="0"/>
            <el-select v-model="form.duration_type" style="width: 100px;margin-left: 10px;">
              <el-option
                label="天"
                :value="3" />
              <el-option
                label="小时"
                :value="2" />
              <el-option
                label="分钟"
                :value="1" />
            </el-select>
          </el-form-item>
        </template> -->
        <template v-else-if="['10001','10003'].includes(form.act_fixed_id)">
          <el-form-item label="图片" prop="image">
            <ImgUpload v-model="form.image" :format="['gif', 'svg+xml', 'png', 'jpeg', 'jpg']"/>
          </el-form-item>
        </template>
        <template v-else-if="['login_benefits'].includes(form.act_fixed_id)">
          <el-form-item label="奖品配置" prop="reward_id">
              <el-select v-model="form.reward_id" placeholder="请选择奖品"
                multiple
                filterable
                remote
                :remote-method="getRewardList">
                <el-option v-for="item in rewardOptionList.filter(item => item.status === 'valid')" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
          </el-form-item>
          <el-form-item  prop="reward_id">
            <template slot="label">
              <el-tooltip>
                <div slot="content">
                  <div>开启后，用户需要在客户端手动领取奖励，</div>
                  <div>关闭后，后端若实现了这个活动场景，用户打开客户端后满足条件时自动领取奖品</div>
                </div>
                <div style="display: flex;align-items: center">
                  <div>手动领取</div>
                  <i class="el-icon-question"></i>
                </div>
              </el-tooltip>
            </template>
            <el-switch
              v-model="form.setting.allow_draw_reward">
            </el-switch>
          </el-form-item>
        </template>

      </el-form>
      <div slot="footer"
        class="dialog-footer">
        <el-button type="primary"
          @click="submitForm">{{ form.id ? '确认修改' : '确认新增' }}</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 end -->

    <!-- 查看对话框 start -->
    <el-dialog :visible.sync="detailOpen" width="700px">
      <div slot="title">查看活动 <el-button type="text" @click="handleShowRecordList">奖品领取记录</el-button></div>
      <el-form class="detail-info" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="活动:">
              <span>{{ detailInfo.act_fixed_id|translateToName(activityOpts) }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最低版本:">
              <span>{{ detailInfo.min_version }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="活动名称:">
          <span>{{ detailInfo.name }}</span>
        </el-form-item>

        <template v-if="detailInfo.act_fixed_id === 'markup-price'">
          <el-row>
            <el-col :span="12">
              <el-form-item label="价格:">
                <span>{{ detailInfo.setting.price|formatMoney }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="划线展示价:">
                <span>{{ detailInfo.setting.origin_price|formatMoney }}</span>
              </el-form-item>
            </el-col>
            <el-col >
              <el-form-item label="展示形式:">
                <span>{{ detailInfo.setting['show-type']}}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </template>

        <el-form-item label="活动标题:" v-if="['limit_t_dis'].includes(detailInfo.act_fixed_id)">
          <span>{{ detailInfo.setting.title }}</span>
        </el-form-item>
        <el-form-item label="活动描述:">
          <span>{{ detailInfo.describe }}</span>
        </el-form-item>

        <el-form-item label="项目:">
          <template v-if="detailInfo.app_id">
            <span v-for="(it, i) in detailInfo.app_id" :key="i">
              {{ i ? ',' : '' }}
              {{ it|translateToName(permission_projectList,'app_id','name') }}
            </span>
          </template>
          <template v-else>
            <span>全部</span>
          </template>
        </el-form-item>

        <el-form-item label="渠道:">
          <template v-if="detailInfo.channel_id">
            <span v-for="(it, i) in detailInfo.channel_id" :key="i">
              {{ i ? ',' : '' }}
              {{ it }}
            </span>
          </template>
          <template v-else>
            <span>全部</span>
          </template>
        </el-form-item>

        <template v-if="['10004','limit_t_dis','pg-code','markup-price'].includes(detailInfo.act_fixed_id)">
          <el-form-item label="权益套餐:">
            <template v-if="detailInfo.product_ids">
              <span v-for="(it, i) in detailInfo.product_ids" :key="i">
                {{ i ? ',' : '' }}
                {{ it|translateToName(productData, 'id', 'show_name') }}
              </span>
            </template>
          </el-form-item>
          <el-row>
          <template v-if="detailInfo.act_fixed_id === '10004'">
            <el-col :span="12">
              <el-form-item label="新用户价格:">
                <span>{{ detailInfo.new_user_price|formatMoney }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="老用户价格:">
                <span>{{ detailInfo.old_user_price|formatMoney }}</span>
              </el-form-item>
            </el-col>
          </template>
          <template v-else-if="detailInfo.act_fixed_id === 'limit_t_dis'">
            <el-col :span="12">
              <el-form-item label="秒杀价">
                <span>{{ detailInfo.setting.price|formatMoney }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="用户分群">
                <span v-for="(it, i) in detailInfo.ug_ids" :key="i">
                  {{ i ? ',' : '' }}
                  {{ it }}
                </span>
              </el-form-item>
            </el-col>
          </template>
          <template v-else-if="['pg-code','markup-price'].includes(detailInfo.act_fixed_id)">
            <el-col :span="12">
              <el-form-item label="奖品配置:">
                <span v-for="item in detailInfo.reward_items" :key="item.id">{{item.name}};</span>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
        </template>

        <template v-if="['login_benefits'].includes(detailInfo.act_fixed_id)">
          <el-form-item label="奖品配置:">
            <span v-for="item in detailInfo.reward_items" :key="item.id">{{item.name}};</span>
          </el-form-item>
        </template>

        <template v-if="['login_benefits'].includes(detailInfo.act_fixed_id)">
          <el-form-item label="手动领取:">
            <span>{{detailInfo.setting.allow_draw_reward}}</span>
          </el-form-item>
        </template>

        <el-row>
          <el-col :span="15">
            <el-form-item label="活动时间:">
              <span>{{ detailInfo.start_time|parseTime }} ~ {{ detailInfo.stop_time|parseTime }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="状态:">
              <el-tag :type="detailInfo.status === 2 ? 'success':'info'"
                disable-transitions>{{ detailInfo.status|translateToName(statusOpts) }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="图片:" v-if="detailInfo.image">
          <a :href="detailInfo.image" target="_blank">
            <img :src="detailInfo.image" alt="" style="max-width: 150px; max-height: 150px;"/>
          </a>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 查看对话框 end -->
    <!-- 领取记录 -->
    <RewardRecord :visible.sync="showObtainRecord" :actId="detailInfo.id"></RewardRecord>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import ImgUpload from '@/components/img-upload'
import { productList } from '@/api/member/product'
import { getChannelByAppId } from '@/api/system/channel'
import { listActivity, addActivity, changeActivity, updateActivity } from '@/api/activity-mg'
import { listUserGroup } from '@/api/user-clustering'
import { getRewardList } from '@/api/reward-manage'
import Editor from '@/components/Editor'
import RewardRecord from './components/rewardRecord'
import { formatMoney } from '@/utils'
export default {
  name: 'ActivityMg',
  components: {
    ImgUpload,
    RewardRecord,
    Editor
  },
  data () {
    return {
      channelOpts: [],
      userGroupList: [],
      activityOpts: [
        // { value: '10003', label: '通用活动' }
      ],
      statusOpts: [
        { value: 1, label: '未开始' },
        { value: 2, label: '进行中' },
        { value: 3, label: '已结束' }
      ],
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      list: null,
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        status: 0,
        dateRange: null,
        channel_id: [],
        keyword: undefined
      },
      detailOpen: false,
      detailInfo: {},
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        act_fixed_id: '',
        name: '',
        describe: '',
        ug_ids: [],
        app_id: [],
        channel_id: [],
        min_version: '',
        dateRange: [],
        image: '',

        product_ids: [],
        new_user_price: 0,
        old_user_price: 0,
        setting: {
          price: undefined,
          title: '',
          msg_title: '',
          origin_price: undefined,
          'show-type': 1,
          allow_draw_reward: true// 是否允许用户领取
        },
        reward_id: '',
        template: '',
        title: ''
        // duration: 0,
        // duration_type: 1
      },
      // 表单校验
      rules: {
        act_fixed_id: [
          { required: true, message: '活动类型不能为空', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '活动名不能为空', trigger: 'blur' }
        ],
        setting: {
          // title: [
          //   { required: true, message: '活动标题不能为空', trigger: 'blur' }
          // ]
        },
        describe: [
          { required: true, message: '活动描述不能为空', trigger: 'blur' }
        ],
        app_id: [
          { required: true, type: 'array', message: '项目不能为空', trigger: 'blur' }
        ],
        ug_ids: [
          { max: 10, type: 'array', message: '最多可选10个用户分群', trigger: 'change' }
        ],
        dateRange: [
          { required: true, type: 'array', message: '活动时间不能为空', trigger: 'blur' }
        ],
        min_version: [
          { required: true, message: '请输入最低版本', trigger: 'blur' }
        ],
        product_ids: [
          { required: true, type: 'array', message: '权益套餐不能为空', trigger: 'blur' }
        ]
      },

      productData: [],
      showObtainRecord: false,
      rewardOptionList: [],
      productOriginPrice: 0,
      productPrice: 0
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList'])
  },
  created () {
    this.getChannels()
    this.getRewardList()
    this.getDicts('act_fixed_id').then(res => {
      this.activityOpts = (res.data || []).map(item => ({
        label: item.dictLabel,
        value: item.dictValue
      }))
      // this.activityOpts.unshift({ value: '10006', label: '免费试用' })
      if (!this.open) {
        this.form.act_fixed_id = this.activityOpts[0].value
      }

      if (this.activityOpts.some(it => it.value === '10004' || it.value === 'limit_t_dis')) {
        this.getProductOps()
      }
    })
    this.emptyForm = JSON.parse(JSON.stringify(this.form))
    this.getList()
  },
  methods: {
    handleShowRecordList () {
      this.showObtainRecord = true
    },
    getRewardList (keyword = '') {
      getRewardList({
        page: 1,
        page_size: 10000,
        keyword
      }).then(res => {
        this.rewardOptionList = res.data.list
      })
    },
    getUserGroupList () {
      if (!this.form.app_id || this.form.app_id.length < 1) {
        this.userGroupList = []
        return
      }
      listUserGroup({
        page: 1,
        page_size: 100,
        status: 'publish',
        appid: this.form.app_id.join(',')
      }).then(res => {
        this.userGroupList = res.data.list || []
      })
    },
    getChannels () {
      const list = this.permission_projectList.map(item => item.app_id)
      getChannelByAppId({ app_ids: list.join(',') }).then(res => {
        const channelList = res.data.list
        for (const item of this.permission_projectList) {
          item.label = item.name
          item.value = parseInt(item.app_id)
          const list = channelList.filter(item1 => item1.app_id === item.value)
          item.children = list.map(item => ({ label: `${item.name}(${item.channel_id})`, value: item.channel_id }))
        }
        this.channelList = channelList
        this.channelOpts = this.permission_projectList
      })
    },
    /** 查询列表 */
    getList () {
      this.loading = true
      const params = Object.assign({}, this.queryParams)
      if (params.dateRange) {
        params.begin_time = params.dateRange[0]
        params.end_time = params.dateRange[1]
      }
      if (!params.channel_id.length) {
        delete params.channel_id
      }
      delete params.dateRange
      listActivity(params).then(response => {
        this.list = response.data.list
        this.total = response.data.count || 0
      }
      ).finally(() => {
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },

    /** 表单重置 */
    reset () {
      this.resetForm('form')
      this.form = { ...this.emptyForm }
    },
    canEdit (row) {
      const editableTypes = this.activityOpts.map(item => item.value)
      // 状态为未开始(1)、进行中(2)、已结束(3)都可以编辑
      return editableTypes.includes(row.act_fixed_id) && [1, 2, 3].includes(row.status)
    },
    handleEdit (row) {
      if (!this.canEdit(row)) return
      const { setting, ...other } = row
      let parsedSetting = {}
      try {
        parsedSetting = setting ? JSON.parse(setting) : {}
      } catch (e) {
        parsedSetting = {}
      }

      if (parsedSetting.price) {
        parsedSetting.price = parsedSetting.price / 100
      }

      if (parsedSetting.origin_price) {
        parsedSetting.origin_price = parsedSetting.origin_price / 100
      }

      this.form = {
        ...other,
        ...parsedSetting,
        setting: parsedSetting,
        id: row.id,
        dateRange: []
      }
      // 时间区间处理
      if (row.dateRange) {
        this.form.dateRange = row.dateRange
      } else if (row.start_time && row.stop_time) {
        this.form.dateRange = [row.start_time, row.stop_time]
      }

      if (row.new_user_price) {
        this.form.new_user_price = row.new_user_price / 100
      }

      if (row.old_user_price) {
        this.form.old_user_price = row.old_user_price / 100
      }

      this.open = true
      this.title = '编辑活动'
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      if (this.form.setting) {
        this.form.setting.price = 0
      }
      this.open = true
      this.title = '添加活动'
      this.form.id = undefined

      this.getChannels()
      this.getRewardList()
      this.getUserGroupList()
    },
    /** 查看按钮操作 */
    handleDetail (row) {
      const { setting, ...other } = row
      const resSetting = setting && JSON.parse(setting)
      this.detailInfo = { ...other,
        ...{
          setting: {
            price: resSetting ? resSetting.price : 0,
            title: resSetting ? resSetting.title : '',
            allow_draw_reward: resSetting?.allow_draw_reward ? '开启' : '关闭',
            origin_price: resSetting ? resSetting.origin_price : '',
            'show-type': resSetting['show-type'] === 1 ? '单选' : '多选'
          }
        }
      }

      console.log('detailinfo', this.detailInfo)
      this.detailOpen = true
    },
    // eslint-disable-next-line sonarjs/cognitive-complexity
    getSubmitParam () {
      const params = JSON.parse(JSON.stringify(this.form))
      if (params.channel_id?.length === this.channelList.length) {
        params.channel_id = []
      }
      if (params.dateRange) {
        params.start_time = params.dateRange[0]
        params.stop_time = params.dateRange[1]
      }
      if (['10004'].includes(params.act_fixed_id)) {
        params.new_user_price = Math.round(params.new_user_price * 100)
        params.old_user_price = Math.round(params.old_user_price * 100)
      } else {
        delete params.new_user_price
        delete params.old_user_price
      }
      // eslint-disable-next-line
      if (['limit_t_dis', 'vip-discount'].includes(params.act_fixed_id)) {
        if (params.product_ids.length > 1) {
          return this.msgError('限时优惠活动中，只能选择一个权益套餐')
        }
        params.setting.price = Math.ceil(params.setting.price * 100)
        params.setting = JSON.stringify(params.setting)
      }
      // eslint-disable-next-line
      if (['pg-code', 'markup-price'].includes(params.act_fixed_id)) {
        params.setting = JSON.stringify({
          msg_title: this.form.setting.msg_title
        })
        const keyWord = '$' + '{' + 'code' + '}'
        if (!params.template.includes(keyWord)) {
          this.msgError(`模板内容缺乏关键字${keyWord}`)
          return
        }
        if (params.act_fixed_id === 'markup-price') {
          params.setting = JSON.stringify({
            msg_title: this.form.setting.msg_title,
            price: Math.round((this.form.setting.price || 0) * 100),
            origin_price: Math.round((this.form.setting.origin_price || 0) * 100),
            'show-type': this.form.setting['show-type']
          })
          if (Number(this.form.setting.price || 0) === 0 && Number(this.form.setting['show-type']) === 1) {
            this.msgError(`当金额为0时，展现形式只能选择“同时选中多个”`)
            return
          }
        }
      } else if (['login_benefits'].includes(params.act_fixed_id)) {
        params.setting = JSON.stringify({
          allow_draw_reward: this.form.setting.allow_draw_reward
        })
        delete params.template
      } else {
        delete params.template
        delete params.reward_id
      }
      if (!['limit_t_dis', '10004', 'pg-code', 'vip-discount', 'markup-price'].includes(params.act_fixed_id)) {
        delete params.product_ids
      }
      if (!['limit_t_dis', 'pg-code', 'login_benefits', 'vip-discount', 'markup-price'].includes(params.act_fixed_id)) {
        delete params.setting
      }
      delete params.dateRange
      return params
    },
    /** 提交按钮 */
    submitForm () {
      // eslint-disable-next-line sonarjs/cognitive-complexity
      this.$refs['form'].validate(valid => {
        if (!valid) return
        const params = this.getSubmitParam()

        const apiFn = params.id ? updateActivity : addActivity
        apiFn(params).then(() => {
          this.msgSuccess(`${params.id ? '修改' : '新增'}成功`)
          this.open = false
          this.getList()
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete ({ id, name }) {
      const { pageIndex, pageSize } = this.queryParams
      this.$confirm('是否确认删除"' + name + '"?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeActivity({ id, action: 'del' }).then(() => {
          this.queryParams.pageIndex = this.getCurrentPage({ total: this.total, pageSize, pageIndex })
          this.getList()
          this.msgSuccess('删除成功')
        })
      })
    },
    /** 结束活动按钮操作 */
    handleStop ({ id, name }) {
      this.$confirm('是否确认结束"' + name + '"?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeActivity({ id, action: 'stop' }).then(() => {
          this.getList()
          this.msgSuccess('活动结束设置成功')
        })
      })
    },
    getProductOpsByAppId () {
      this.getUserGroupList()
      if (this.form.act_fixed_id === 'limit_t_dis') {
        this.getProductOps(this.form.app_id, 1)
      } else {
        this.getProductOps()
      }
    },
    getProductOps (bind_app_ids, status) {
      const param = {
        bind_app_id: null,
        status: status || 10,
        page: 1,
        page_size: 1000,
        keyword: ''
      }
      productList(param).then(res => {
        this.productData = res.data.list || []
        if (bind_app_ids && bind_app_ids.length) {
          this.productData = this.productData.filter(item => bind_app_ids.includes(item.bind_app_id))
        }
      })
    },
    setProductPrice (ids) {
      // 限时优惠活动只会关联一个套餐
      if (ids.length === 1) {
        const productItem = this.productData.filter(item => item.id === ids[0])[0]
        this.productOriginPrice = formatMoney(productItem?.origin_price)
        this.productPrice = formatMoney(productItem?.price)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.ql-editor {
  padding: 0;
  overflow-y: unset;
}
.input-form-fill /deep/ .el-tag.el-tag--info {
    display: flex;
    align-items: baseline;
  .el-select__tags-text {
    display: inline-block;
    max-width: 380px;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
<style lang="scss">
.w500 {
  width: 550px;
}

.activity-add-edit-dialog {
  margin-top: 5vh !important;
}
</style>
